package com.mewpipe.dao.jpa;

import java.awt.Dimension;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import com.mewpipe.dao.LnkUserVideoDao;
import com.mewpipe.entity.LnkUserVideo;
import com.mewpipe.entity.User;

public class JpaLnkUserVideoDao implements LnkUserVideoDao {
	private EntityManagerFactory emf;

	public JpaLnkUserVideoDao(EntityManagerFactory emf) {

		this.emf = emf;

	}

	@Override
	public void addLink(long _IdUser, long _IdVideo) {
		EntityManager em = emf.createEntityManager();
		LnkUserVideo newlink = new LnkUserVideo(_IdUser, _IdVideo);

		try {
			em.getTransaction().begin();
			em.persist(newlink);
			em.getTransaction().commit();

		}

		finally {
			if (em.getTransaction().isActive())
				em.getTransaction().rollback();
			em.close();

		}

	}

	@Override
	public long findUserByVideo(long IdVideo) {
		long iduser = -1;
		EntityManager em = emf.createEntityManager();
		Query query = em
				.createQuery("SELECT UserID FROM LnkUserVideo WHERE VideoID ='"
						+ IdVideo + "'");
		try {
			em.getTransaction().begin();
			List users = query.getResultList();
			if (!users.isEmpty())
				iduser = (long) users.get(0);
			else
				iduser = -1;
			em.getTransaction().commit();
		}

		finally {
			if (em.getTransaction().isActive())
				em.getTransaction().rollback();
			em.close();

		}

		return iduser;
	}
}
